package cn.lsp.sharkmall.service.impl;

import cn.lsp.sharkmall.common.ServiceResultEnum;
import cn.lsp.sharkmall.mapper.AdminUserMapper;
import cn.lsp.sharkmall.mapper.AdminUserTokenMapper;
import cn.lsp.sharkmall.pojo.dto.AdminAddNewDTO;
import cn.lsp.sharkmall.pojo.entity.AdminUser;
import cn.lsp.sharkmall.pojo.entity.AdminUserToken;
import cn.lsp.sharkmall.pojo.vo.AdminVO;
import cn.lsp.sharkmall.service.IAdminUserService;
import cn.lsp.sharkmall.util.NumberUtil;
import cn.lsp.sharkmall.util.PageQueryUtil;
import cn.lsp.sharkmall.util.PageResult;
import cn.lsp.sharkmall.util.SystemUtil;
import org.hibernate.validator.internal.util.logging.Log_$logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import cn.lsp.sharkmall.config.handler.ServiceException;
import cn.lsp.sharkmall.util.ServiceCode;

/**
 * @Description: 管理员服务层实现类
 * @Author: sweeterjava@163.com
 * @Date: 2023/2/12
 * @Time: 23:52
 */

@Service
public class IAdminUserServiceImpl implements IAdminUserService {
    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private AdminUserTokenMapper adminUserTokenMapper;

    /**
     * 管理员登录
     *
     * @param userName
     * @param password
     * @return
     */
    @Override
    public String login(String userName, String password) {
        AdminUser loginAdminUser = adminUserMapper.login(userName, password);
        if (loginAdminUser != null) {
            //登录后即执行修改token的操作
            String token = getNewToken(System.currentTimeMillis() + "", loginAdminUser.getAdminUserId());
            AdminUserToken adminUserToken = adminUserTokenMapper.selectByPrimaryKey(loginAdminUser.getAdminUserId());
            //当前时间
            Date now = new Date();
            //过期时间
            Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);//过期时间 48 小时
            if (adminUserToken == null) {
                adminUserToken = new AdminUserToken();
                adminUserToken.setAdminUserId(loginAdminUser.getAdminUserId());
                adminUserToken.setToken(token);
                adminUserToken.setUpdateTime(now);
                adminUserToken.setExpireTime(expireTime);
                //新增一条token数据
                if (adminUserTokenMapper.insertSelective(adminUserToken) > 0) {
                    //新增成功后返回
                    return token;
                }
            } else {
                adminUserToken.setToken(token);
                adminUserToken.setUpdateTime(now);
                adminUserToken.setExpireTime(expireTime);
                //更新
                if (adminUserTokenMapper.updateByPrimaryKeySelective(adminUserToken) > 0) {
                    //修改成功后返回
                    return token;
                }
            }

        }
        return ServiceResultEnum.LOGIN_ERROR.getResult();
    }


    /**
     * 获取token值
     *
     * @param timeStr
     * @param userId
     * @return
     */
    private String getNewToken(String timeStr, Long userId) {
        String src = timeStr + userId + NumberUtil.genRandomNum(6);
        return SystemUtil.genToken(src);
    }

    /**
     * 获取用户信息
     *
     * @param loginUserId
     * @return
     */
    @Override
    public AdminUser getUserDetailById(Long loginUserId) {
        return adminUserMapper.selectByPrimaryKey(loginUserId);
    }

    /**
     * 修改当前登录用户的密码
     *
     * @param loginUserId
     * @param originalPassword
     * @param newPassword
     * @return
     */
    @Override
    public Boolean updatePassword(Long loginUserId, String originalPassword, String newPassword) {
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(loginUserId);
        //当前用户非空才可以进行更改
        if (adminUser != null) {
            //比较原密码是否正确
            if (originalPassword.equals(adminUser.getLoginPassword())) {
                //设置新密码并修改
                adminUser.setLoginPassword(newPassword);
                if (adminUserMapper.updateByPrimaryKeySelective(adminUser) > 0 && adminUserTokenMapper.deleteByPrimaryKey(loginUserId) > 0) {
                    //修改成功且清空当前token则返回true
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 修改当前登录用户的名称
     *
     * @param loginUserId
     * @param loginUserName
     * @param nickName
     * @return
     */
    @Override
    public Boolean updateName(Long loginUserId, String loginUserName, String nickName) {
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(loginUserId);
        //当前用户非空才可以进行更改
        if (adminUser != null) {
            //设置新名称并修改
            adminUser.setLoginUserName(loginUserName);
            adminUser.setNickName(nickName);
            if (adminUserMapper.updateByPrimaryKeySelective(adminUser) > 0) {
                //修改成功则返回true
                return true;
            }
        }
        return false;
    }

    /**
     * 退出登录
     *
     * @param adminUserId
     * @return
     */
    @Override
    public Boolean logout(Long adminUserId) {
        return adminUserTokenMapper.deleteByPrimaryKey(adminUserId) > 0;
    }

    /**
     * 添加管理员
     */
    @Override
    public void addNew(AdminAddNewDTO adminAddNewDTO) {
        AdminUser adminUser = new AdminUser();
        adminUser.setLoginUserName(adminAddNewDTO.getUserName());
        adminUser.setLoginPassword(adminAddNewDTO.getPassword());
        adminUser.setNickName(adminAddNewDTO.getNickName());
        adminUser.setLocked((adminAddNewDTO.getLocked()));
        adminUserMapper.insert(adminUser);
    }
    
    /**
     * 获取管理员列表
     */
    @Override
    public List<AdminVO> list() {
        List<AdminVO> list = adminUserMapper.list();
        return list;
    }

    /**
     * 删除管理员
     */
    @Override
    public void delete(Long id) {
        // 调用adminMapper的deleteById()方法，执行删除管理员数据，获取返回值
        int rows = adminUserMapper.deleteById(id);
        // 判断以上返回的受影响行数是否不等于1
        if (rows < 1) {
            String message = "删除管理员失败，服务器忙，请稍后再次尝试！";
            // 是：抛出异常（ERR_DELETE：服务器忙）
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }



}
